package cn.edu.xmu.orderpayment.order.mq.listener;

import cn.edu.xmu.oomall.core.util.ReturnObject;
import cn.edu.xmu.orderpayment.order.constant.Constants;
import cn.edu.xmu.orderpayment.order.dao.OrderDao;
import cn.edu.xmu.orderpayment.order.microservice.CustomerService;
import cn.edu.xmu.orderpayment.order.microservice.vo.CustomerModifyPointsVo;
import cn.edu.xmu.orderpayment.order.model.bo.Order;
import cn.edu.xmu.orderpayment.order.model.bo.OrderItem;
import cn.edu.xmu.orderpayment.order.model.po.OrderItemPo;
import cn.edu.xmu.orderpayment.order.model.po.OrderPo;
import cn.edu.xmu.privilegegateway.annotation.util.InternalReturnObject;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQPushConsumerLifecycleListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static cn.edu.xmu.privilegegateway.annotation.util.Common.cloneVo;

/**
 * @Author: Li Yixuan 22920192204232
 * @Date: 2021/12/28
 */
@Service
@RocketMQMessageListener(topic = "order-refund-topic2", consumeMode = ConsumeMode.CONCURRENTLY, consumeThreadMax = 10, consumerGroup = "order-refund-group2")
public class OrderRefundListener implements RocketMQListener<String>, RocketMQPushConsumerLifecycleListener {
    private static final Logger logger = LoggerFactory.getLogger(OrderRefundListener.class);

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private CustomerService customerService;


    @Override
    public void onMessage(String documentId) {
        logger.info(LocalDateTime.now()+documentId+"收到了退款成功的消息,开始处理订单");

        RequestContextHolder.setRequestAttributes(Constants.servletRequestAttributes);

        String orderSn = null;
        if(documentId.endsWith("-D")||documentId.endsWith("-W")){
            orderSn = documentId.substring(0, documentId.length() - 2);
        }
        else orderSn=documentId;

        ReturnObject<Order> ret = orderDao.getOrderByOrderSn(orderSn);
        if (ret.getData() == null) return;
        Order order = cloneVo(ret.getData(),Order.class);
        if (!order.getState().equals(Order.State.WAIT_REFUND.getCode())) return;

        order.setState(Order.State.HAS_REFUNDED.getCode());
        orderDao.updateOrder(order, order.getCreatorId(), order.getCreatorName());

        // 获得所有子订单
        List<Order> subOrders=new ArrayList<>();
        ReturnObject ret3 = orderDao.getOrderByPid(order.getId());
        List<OrderPo> orderPos = (List<OrderPo>) ret3.getData();
        for(OrderPo orderPo:orderPos){
            Order subOrder = cloneVo(orderPo,Order.class);
            subOrders.add(subOrder);
        }
        // 获得所有item
        List<OrderItem> orderItemList=new ArrayList<>();
        if(subOrders.size()==0) {
            ReturnObject<List> orderItemListRet = orderDao.getOrderItemsByOrderId(order.getId());
            orderItemList=orderItemListRet.getData();
        } else{
            for(Order subOrder:subOrders){
                ReturnObject<List> orderItemListRet = orderDao.getOrderItemsByOrderId(subOrder.getId());
                List<OrderItemPo> tempList=orderItemListRet.getData();
                for(OrderItemPo orderItem:tempList) {
                    orderItemList.add(cloneVo(orderItem, OrderItem.class));
                }
            }
        }

        String customerName=customerService.getCustomerById(order.getCustomerId()).getData().getName();

        // 退积点和优惠券
        CustomerModifyPointsVo customerModifyPointsVo=new CustomerModifyPointsVo();
        //退积点，正数
        customerModifyPointsVo.setPoints(order.getPoint());
        customerService.changeCustomerPoint(order.getCustomerId(), customerModifyPointsVo);
        for(OrderItem orderItem:orderItemList){
            if(orderItem.getCouponId()!=null) {
                customerService.refundCoupon(order.getCustomerId(),customerName,orderItem.getCouponId());
            }
        }

        if(subOrders.size()!=0){
            for(Order subOrder:subOrders){
                subOrder.setState(Order.State.HAS_REFUNDED.getCode());
                orderDao.updateOrder(subOrder, order.getCreatorId(), order.getCreatorName());
            }
        }
    }

    @Override
    public void prepareStart(DefaultMQPushConsumer defaultMQPushConsumer) {

    }


}
